package com.example.xyxwebbackend001.controller;



import com.example.xyxwebbackend001.common.CommonResult;
import com.example.xyxwebbackend001.config.FileUploadConfig;
import com.example.xyxwebbackend001.model.DTO.*;
import com.example.xyxwebbackend001.model.entity.CPosts;
import com.example.xyxwebbackend001.model.entity.ContentBlock;
import com.example.xyxwebbackend001.model.entity.HomeImagesData;
import com.example.xyxwebbackend001.model.entity.User;
import com.example.xyxwebbackend001.model.vo.*;
import com.example.xyxwebbackend001.service.*;
import com.example.xyxwebbackend001.util.FileUploadUtil;
import jakarta.validation.Valid;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Stream;

@RestController
@RequestMapping("/mana")
public class ManaController {
    @Autowired
    private UserService userService;

    @Autowired
    private CPostsService cPostsService;

    @Autowired
    private FileUploadConfig fileUploadConfig;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private HomeService homeService;

    @Autowired
    private ManaService manaService;
    // 上传图片
    @PostMapping(value = "/articles/upload",
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public CommonResult<Map<String, Object>> uploadImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "articleToken", required = false) String articleToken) {
        try {
            if (file.isEmpty()) {
                return CommonResult.fail(400, "上传文件不能为空");
            }

            // 生成/验证存储token
            String storageToken = (articleToken != null && !articleToken.isEmpty()) ?
                    articleToken : UUID.randomUUID().toString();

            Path uploadDir = Paths.get(fileUploadConfig.getUploadDir(), "temp", storageToken);
            Files.createDirectories(uploadDir);

            String fileName = String.format("%s_%s",
                    UUID.randomUUID(),
                    Paths.get(file.getOriginalFilename()).getFileName().toString());

            // 写入文件
            Files.write(uploadDir.resolve(fileName), file.getBytes());

            return CommonResult.success(Map.of(
                    "url", String.format("/files/cult/temp/%s/%s", storageToken, fileName),
                    "articleToken", storageToken
            ));
        } catch (IOException e) {
            return CommonResult.error("文件存储失败: " + e.getMessage());
        }
    }

    // 删除图片
    @DeleteMapping("/articles/upload/delete")
    public CommonResult<Boolean> deleteUploadedFile(
            @RequestBody FileDeleteRequestDTO fileDeleteRequestDTO) {
        try {
            String fileName = fileDeleteRequestDTO.getFileName();
            String articleToken = fileDeleteRequestDTO.getArticleToken();
            // 构建安全文件路径
            Path filePath = Paths.get(fileUploadConfig.getUploadDir(),
                    "temp",
                    articleToken,
                    fileName).normalize();

            if (!filePath.startsWith(Paths.get(fileUploadConfig.getUploadCultDir()))) {
                return CommonResult.fail(403, "非法文件路径");
            }

            if (Files.exists(filePath)) {
                Files.delete(filePath);
                Path parentDir = filePath.getParent();
                if (Files.isDirectory(parentDir) && Files.list(parentDir).count() == 0) {
                    Files.delete(parentDir);
                }
                return CommonResult.success(true);
            }
            return CommonResult.fail(404, "文件不存在");
        } catch (IOException e) {
            return CommonResult.error("删除失败: " + e.getMessage());
        } catch (Exception e) {
            return CommonResult.error("系统异常: " + e.getMessage());
        }
    }

    // 发布文章
    @PostMapping(value = "/articles/publish", produces = MediaType.APPLICATION_JSON_VALUE)
    public CommonResult<Object> createArticle(@RequestBody ArticleRequestDTO request) {

        try {
            // 保存文章并获取ID
            Integer articleId = cPostsService.publishCPost(request);

            // 迁移临时文件到正式目录
            if (request.getArticleToken() != null && !request.getArticleToken().isEmpty()) {
                migrateAllTempFiles(request.getArticleToken(), articleId);
            }

            return CommonResult.tip("发布成功！");
        } catch (Exception e) {
            return CommonResult.error("系统异常: " + e.getMessage());
        }
    }
    private void migrateAllTempFiles(String articleToken, Integer articleId) throws IOException {
        Path sourceDir = Paths.get(fileUploadConfig.getUploadDir(), "temp", articleToken);
        Path targetDir = Paths.get(fileUploadConfig.getUploadCultDir(), "published", articleId.toString());

        if (Files.exists(sourceDir)) {
            // 创建目标目录
            Files.createDirectories(targetDir);

            // 移动所有文件
            try (Stream<Path> files = Files.list(sourceDir)) {
                files.forEach(source -> {
                    try {
                        String[] nameParts = source.getFileName().toString().split("_", 2);
                        String originalName = nameParts.length > 1 ? nameParts[1] : nameParts[0];

                        Path dest = targetDir.resolve(originalName);
                        Files.move(source, dest, StandardCopyOption.REPLACE_EXISTING);
                    } catch (IOException e) {
                        throw new RuntimeException("文件迁移失败: " + e.getMessage(), e);
                    }
                });
            }

            // 清理临时目录
            Files.deleteIfExists(sourceDir);
        }
    }
    // 获取获取用户信息
    @GetMapping("/user/info/list")
    public CommonResult<Object> getUserInfo(
            @RequestParam(required = false) String keyword) {
        List<UserInfoVO> users = userService.getUsersByRole("USER", keyword);
        return CommonResult.message(users);
    }
    //  重置密码
    @PostMapping("/user/resetPassword")
    public CommonResult<Object> resetPassword(@RequestParam Integer userId) {
        try {
            userService.resetPassword(userId);
            return CommonResult.success("密码重置成功");
        } catch (Exception e) {
            return CommonResult.error("密码重置失败: " + e.getMessage());
        }
    }

    @PutMapping("/user/update-status")
    public CommonResult<Object> updateUserStatus(@RequestParam Integer userId, @RequestParam Integer status) {
        try {
            userService.updateUserStatus(userId, status);
            return CommonResult.success("操作成功");
        } catch (Exception e) {
            return CommonResult.error("操作失败: " + e.getMessage());
        }
    }

//    获取文章列表
    @GetMapping("/articles/list")
    public CommonResult<List<ArticleListVO>> getCPostsList(
            @RequestParam(required = false) String keyword
    ) {
        // 调用服务层方法获取数据
        List<ArticleListVO> posts = cPostsService.getCPostsList(keyword);
        return CommonResult.message(posts);
    }

//    调整文章状态
    @PostMapping("/articles/status")
    public CommonResult<Object> updateArticleStatus(
            @RequestParam Integer articleId,
            @RequestParam Integer status
    ) {
        try {
            cPostsService.updateArticleStatus(articleId, status);
            return CommonResult.success("文章状态更新成功");
        } catch (Exception e) {
            return CommonResult.error("文章状态更新失败: " + e.getMessage());
        }
    }
    @PutMapping("/{id}/{action}")
    public CommonResult<Object> updateCarouselStatus(
            @PathVariable Integer id,
            @PathVariable String action) {

        Integer status = switch (action.toLowerCase()) {
            case "delete" -> 2;
            case "publish" -> 1;
            case "unpublish" -> 0;
            default -> throw new IllegalArgumentException("无效操作");
        };

        homeService.updateCarouselStatus(id, status);
        return CommonResult.tip("操作成功");
    }
    @PostMapping("/carousel/upload")
    public CommonResult<String> uploadCarousel(
            @RequestParam("file") MultipartFile file) {
        try {
            String fileName = fileStorageService.storeFiles(new MultipartFile[]{file}, "home").get(0);
            return CommonResult.success(fileName);
        } catch (IOException e) {
            return CommonResult.error("上传失败: " + e.getMessage());
        }
    }
    @DeleteMapping("/carousel/delete")
    public CommonResult<String> deleteCarousel(@RequestParam("fileName") String fileName) {
        try {
            fileStorageService.deleteFile(fileName, "home");
            return CommonResult.success("删除成功");
        } catch (Exception e) {
            return CommonResult.error("删除失败: " + e.getMessage());
        }
    }

    @PostMapping("/carousel/add")
    public CommonResult<Void> linkCarouselInfo(
            @RequestParam String fileName,
            @RequestParam String title) {
        try {
            HomeImagesData data = new HomeImagesData();
            data.setTitle(title);
            data.setImagePath(fileName);

            homeService.createCarousel(data);
            return CommonResult.tip("上传成功");
        } catch (Exception e) {
            return CommonResult.error("操作失败: " + e.getMessage());
        }
    }
    @GetMapping("statistics/t-posts/count")
    public CommonResult<Map<String, Object>> getTPostStatistics() {
        Map<String, Object> statistics = manaService.getTPostStatistics();
        return CommonResult.message(statistics);
    }
    @GetMapping("statistics/t-posts/tags")
    public CommonResult<List<Map<String, Object>>> getTagStatistics() {
        List<Map<String, Object>> statistics = manaService.getTagStatistics();
        return CommonResult.message(statistics);
    }
    @GetMapping("statistics/t-posts/cities")
    public CommonResult<List<Map<String, Object>>> getCityStatistics() {
        List<Map<String, Object>> statistics = manaService.getCityStatistics();
        return CommonResult.message(statistics);
    }
    @PostMapping(value = "commend/food/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public CommonResult<Map<String, Object>> uploadFoodFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "articleToken", required = false) String articleToken) {
        try {
            if (file.isEmpty()) {
                return CommonResult.fail(400, "上传文件不能为空");
            }
            return CommonResult.success(FileUploadUtil.uploadFile(file, articleToken));
        } catch (IOException e) {
            return CommonResult.error("文件存储失败: " + e.getMessage());
        }
    }

    @DeleteMapping("commend/food/file/delete")
    public CommonResult<Boolean> deleteFoodFile(
            @RequestBody FileDeleteRequestDTO fileDeleteRequestDTO) {
        try {
            boolean result = FileUploadUtil.deleteFile(
                    fileDeleteRequestDTO.getFileName(),
                    fileDeleteRequestDTO.getArticleToken()
            );
            return result ? CommonResult.success(true) : CommonResult.fail(404, "文件不存在");
        } catch (IOException e) {
            return CommonResult.error("删除失败: " + e.getMessage());
        }
    }
    @PostMapping("/commend/food/publish")
    public CommonResult<Integer> publishFoodWorks(
            @Valid @RequestBody RecPublishDTO request) {
        try {
            // 保存主数据并获取ID
            Integer foodId = manaService.createFoodRec(request);

            if (request.getArticleToken() != null) {
                FileUploadUtil.migrateTempFiles(
                        request.getArticleToken(),
                        "food/" + foodId
                );
            }

            return CommonResult.tip("操作成功");
        } catch (Exception e) {
            return CommonResult.error("发布失败: " + e.getMessage());
        }
    }
    @PostMapping(value = "commend/craft/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public CommonResult<Map<String, Object>> uploadCraftFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "articleToken", required = false) String articleToken) {
        try {
            if (file.isEmpty()) {
                return CommonResult.fail(400, "上传文件不能为空");
            }
            return CommonResult.success(FileUploadUtil.uploadFile(file, articleToken));
        } catch (IOException e) {
            return CommonResult.error("文件存储失败: " + e.getMessage());
        }
    }

    @DeleteMapping("commend/craft/file/delete")
    public CommonResult<Boolean> deleteCraftFile(
            @RequestBody FileDeleteRequestDTO fileDeleteRequestDTO) {
        try {
            boolean result = FileUploadUtil.deleteFile(
                    fileDeleteRequestDTO.getFileName(),
                    fileDeleteRequestDTO.getArticleToken()
            );
            return result ? CommonResult.success(true) : CommonResult.fail(404, "文件不存在");
        } catch (IOException e) {
            return CommonResult.error("删除失败: " + e.getMessage());
        }
    }
    @PostMapping("/commend/craft/publish")
    public CommonResult<Integer> publishCraftWorks(
            @Valid @RequestBody RecPublishDTO request) {
        try {
            Integer trId = manaService.createCraftRec(request);

            if (request.getArticleToken() != null) {
                FileUploadUtil.migrateTempFiles(
                        request.getArticleToken(),
                        "craft/" + trId
                );
            }

            return CommonResult.tip("操作成功");
        } catch (Exception e) {
            return CommonResult.error("发布失败: " + e.getMessage());
        }
    }
    @PostMapping(value = "commend/tourist/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public CommonResult<Map<String, Object>> uploadTouristFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "articleToken", required = false) String articleToken) {
        try {
            if (file.isEmpty()) {
                return CommonResult.fail(400, "上传文件不能为空");
            }
            return CommonResult.success(FileUploadUtil.uploadFile(file, articleToken));
        } catch (IOException e) {
            return CommonResult.error("文件存储失败: " + e.getMessage());
        }
    }

    @DeleteMapping("commend/tourist/file/delete")
    public CommonResult<Boolean> deleteTouristFile(
            @RequestBody FileDeleteRequestDTO fileDeleteRequestDTO) {
        try {
            boolean result = FileUploadUtil.deleteFile(
                    fileDeleteRequestDTO.getFileName(),
                    fileDeleteRequestDTO.getArticleToken()
            );
            return result ? CommonResult.success(true) : CommonResult.fail(404, "文件不存在");
        } catch (IOException e) {
            return CommonResult.error("删除失败: " + e.getMessage());
        }
    }
    @PostMapping("/commend/tourist/publish")
    public CommonResult<Integer> publishTouristWorks(
            @Valid @RequestBody RecPublishDTO request) {
        try {
            Integer trId = manaService.createTouristRec(request);

            if (request.getArticleToken() != null) {
                FileUploadUtil.migrateTempFiles(
                        request.getArticleToken(),
                        "tourist/" + trId
                );
            }

            return CommonResult.tip("操作成功");
        } catch (Exception e) {
            return CommonResult.error("发布失败: " + e.getMessage());
        }
    }
    @GetMapping("/commend/food/list")
    public CommonResult<List<FoodListVO>> getFoodList(
            @RequestParam(required = false) String keyword) {
        List<FoodListVO> list = manaService.getFoodList(keyword);
        return CommonResult.message(list);
    }
    @PutMapping("/commend/food/{id}/{action}")
    public CommonResult<Object> updateFoodStatus(
            @PathVariable Integer id,
            @PathVariable String action) {

        Integer status = switch (action.toLowerCase()) {
            case "delete" -> 2;
            case "publish" -> 1;
            case "unpublish" -> 0;
            default -> throw new IllegalArgumentException("无效操作");
        };

        manaService.updateFoodStatus(id, status);
        return CommonResult.tip("操作成功");
    }
    // 获取手工艺列表
    @GetMapping("/commend/craft/list")
    public CommonResult<List<TradCraftListVO>> getCraftList(
            @RequestParam(required = false) String keyword) {
        List<TradCraftListVO> list = manaService.getTradCraftList(keyword);
        return CommonResult.message(list);
    }
    @PutMapping("/commend/craft/{id}/{action}")
    public CommonResult<Object> updateCraftStatus(
            @PathVariable Integer id,
            @PathVariable String action) {

        Integer status = switch (action.toLowerCase()) {
            case "delete" -> 2;
            case "publish" -> 1;
            case "unpublish" -> 0;
            default -> throw new IllegalArgumentException("无效操作");
        };

        manaService.updateTradCraftStatus(id, status);
        return CommonResult.tip("操作成功");
    }
    // 获取景点列表
    @GetMapping("/commend/tourist/list")
    public CommonResult<List<TouristListVO>> getTouristList(
            @RequestParam(required = false) String keyword) {
        List<TouristListVO> list = manaService.getTouristList(keyword);
        return CommonResult.message(list);
    }
    @PutMapping("/commend/tourist/{id}/{action}")
    public CommonResult<Object> updateTouristStatus(
            @PathVariable Integer id,
            @PathVariable String action) {

        Integer status = switch (action.toLowerCase()) {
            case "delete" -> 2;
            case "publish" -> 1;
            case "unpublish" -> 0;
            default -> throw new IllegalArgumentException("无效操作");
        };

        manaService.updateTouristStatus(id, status);
        return CommonResult.tip("操作成功");
    }
}
